package com.laolang.pluto.module.generator.util;

import cn.hutool.core.util.StrUtil;
import com.laolang.pluto.common.exception.BusinessException;
import com.laolang.pluto.module.generator.consts.logic.GenBizCode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.experimental.UtilityClass;

/**
 * 代码生成工具类
 *
 * @author laolang
 * @date 2021-08-01 21:52
 */
@UtilityClass
public class GenUtil {

    private static final Pattern LINE_PATTERN = Pattern.compile("_(\\w)");

    /**
     * 下划线命名转大驼峰
     */
    public static String underline2UpperHump(String identification) {
        String lowerHump = underline2LowerHump(identification);
        return StrUtil.replace(lowerHump, 0, 1, Character.toUpperCase(lowerHump.charAt(0)));
    }

    /**
     * 下划线转小驼峰
     */
    public static String underline2LowerHump(String identification) {
        identification = identification.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(identification);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String mysqlType2javaType(String mysqlType) {
        String type = mysqlType.toLowerCase();
        if (StrUtil.startWith(type, "varchar") || StrUtil.startWith(type, "char") || "text".equals(type)) {
            return "java.lang.String";
        }
        if (StrUtil.startWith(type, "tinyint") || StrUtil.startWith(type, "smallint")
                || StrUtil.startWith(type, "mediumint") || StrUtil.startWith(type, "int")) {
            return "java.lang.Integer";
        }
        if (StrUtil.startWith(type, "integer") || "id".equals(type) || StrUtil.startWith(type, "bigint")) {
            return "java.lang.Long";
        }
        if ("blob".equals(type)) {
            return "java.lang.byte[]";
        }
        if ("bit".equals(type)) {
            return "java.lang.Boolean";
        }
        if (StrUtil.startWith(type, "decimal")) {
            return "java.math.BigDecimal";
        }
        if ("date".equals(type) || "time".equals(type) || "datetime".equals(type)) {
            return "java.time.LocalDateTime";
        }
        throw new BusinessException(GenBizCode.UNKNOWN_COLUMN_TYPE);
    }
}
